package com.ilink.groundservice.controller.AiX;/**
 * <h3>iLink-java-backend-zhangbo2</h3>
 *
 * @Description <p>微场景创设模块与前端交互接口</p>
 * @Author ZhangBo
 * @Date 2025-01-15 11:32
 **/

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ilink.groundservice.entity.PO.AiX.AiXSceneAuthor;
import com.ilink.groundservice.entity.PO.AiX.AiXSceneBeginEnd;
import com.ilink.groundservice.entity.VO.AiX.AiXSceneResponse;
import com.ilink.groundservice.mapper.AiX.AiXSceneAuthorMapper;
import com.ilink.groundservice.service.AiX.AiXSceneService;
import com.ilink.ilinkapi.client.UserServiceClient;
import com.ilink.ilinkapi.dto.ground.AiX.*;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.ilinkcommon.utils.UserContext;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @ClassName AiXSceneController
 * @Description TODO
 * @Author ZhangBo
 * @Date 2025-01-15 11:32
 **/
@Slf4j
@RequestMapping("/ground/aix/scene")
@RestController
@RequiredArgsConstructor
public class AiXSceneController {
    private final AiXSceneService aiXSceneService;
    private final UserServiceClient userServiceClient;
    
    @MethodLog("分页返回场景元数据，只返回发布了的")
    @GetMapping("/get_scenes")
    public R getScenes(AiXAreaFilterRequest request) {
        try {
            String userId = UserContext.getUserId();
            IPage<AiXSceneResponse> responseIPage = aiXSceneService.getScenes(request, userId);
            if (responseIPage != null) {
                return R.ok("分页返回场景元数据", responseIPage);
            } else {
                return R.error("查询场景数据失败");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    @MethodLog("获取单个场景")
    @GetMapping("/get_scene/{sceneId}")
    public R getScene(@PathVariable Long sceneId) {
        try {
            String userId = UserContext.getUserId(); // 获取当前用户ID
            R permissions = userServiceClient.checkUserScenePermission(userId, sceneId);
            Map<String, Boolean> permissionsMap = (Map<String, Boolean>) permissions.getData();
            if (!permissionsMap.get("view")) {
                log.error("用户没有查看该场景的权限，userId: " + userId + ", sceneId: " + sceneId);
                return R.error("您没有查看该场景的权限");
            }
            AiXSceneResponse response = aiXSceneService.getSceneById(sceneId);
            return R.ok("场景获取成功", response);
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }
    @MethodLog("插入场景元数据")
    @PostMapping("/insert_scene")
    public R insertScene(AiXSceneCardInsertRequest request) {
        try {
            String userId = UserContext.getUserId(); // 获取当前用户ID
            R permissions = userServiceClient.checkUserScenePermission(userId, null);
            Map<String, Boolean> permissionsMap = (Map<String, Boolean>) permissions.getData();
            if (!permissionsMap.get("create")) {
                log.error("用户没有新建场景的权限，userId: " + userId + ", sceneId: " + null);
                return R.error("您没有新建该场景的权限");
            }
            aiXSceneService.insertScene(userId, request);
            return R.ok("场景插入成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    @MethodLog("更新场景卡片数据")
    @PostMapping("/update_scene_card")
    public R updateSceneCard(@RequestBody AiXSceneCardUpdateRequest request) {
        try {
            String userId = UserContext.getUserId(); // 获取当前用户ID
            R permissions = userServiceClient.checkUserScenePermission(userId, request.getSceneId());
            Map<String, Boolean> permissionsMap = (Map<String, Boolean>) permissions.getData();
            if (!permissionsMap.get("edit")) {
                log.error("用户没有编辑该场景的权限，userId: " + userId + ", sceneId: " + request.getSceneId());
                return R.error("您没有编辑该场景的权限");
            }
            return aiXSceneService.updateSceneCard(request);
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }


    @MethodLog("更新场景封面图")
    @PostMapping("/update_scene_cover")
    public R updateSceneCover(MultipartFile file, Long sceneId, Long areaId) {
        try {
            String userId = UserContext.getUserId(); // 获取当前用户ID
            R permissions = userServiceClient.checkUserScenePermission(userId, sceneId);
            Map<String, Boolean> permissionsMap = (Map<String, Boolean>) permissions.getData();
            if (!permissionsMap.get("edit")) {
                log.error("用户没有编辑该场景的权限，userId: " + userId + ", sceneId: " + sceneId);
                return R.error("您没有编辑该场景的权限");
            }
            return aiXSceneService.updateSceneCover(file, sceneId, areaId);
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    @MethodLog("更新场景详情页数据")
    @PostMapping("/update_scene")
    public R updateScene(@RequestBody AiXSceneBaseUpdateRequest request) {
        try {
            String userId = UserContext.getUserId(); // 获取当前用户ID
            R permissions = userServiceClient.checkUserScenePermission(userId, request.getSceneId());
            Map<String, Boolean> permissionsMap = (Map<String, Boolean>) permissions.getData();
            if (!permissionsMap.get("edit")) {
                log.error("用户没有编辑该场景的权限，userId: " + userId + ", sceneId: " + request.getSceneId());
                return R.error("您没有编辑该场景的权限");
            }
            return aiXSceneService.updateSceneBase(request);
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    @MethodLog("获取场景最常用的8个标签标签")
    @GetMapping("/get_scene_tags")
    public R getSceneTags(@RequestParam Long areaId) {
        try {
            List<String> tags = aiXSceneService.getSceneTags(areaId);
            return R.ok("场景最常用的8个标签标签", tags);

        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }

    @MethodLog("删除微场景卡片")
    @PostMapping("/delete_scene/{sceneId}")
    public R deleteScene(@PathVariable Long sceneId) {
        try {
            String userId = UserContext.getUserId(); // 获取当前用户ID
            R permissions = userServiceClient.checkUserScenePermission(userId, sceneId);
            Map<String, Boolean> permissionsMap = (Map<String, Boolean>) permissions.getData();
            if (!permissionsMap.get("edit")) {
                log.error("用户没有删除该场景的权限，userId: " + userId + ", sceneId: " + sceneId);
                return R.error("您没有删除该场景的权限");
            }
            aiXSceneService.deleteScene(sceneId);
            return R.ok("场景删除成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return R.error(e.getMessage());
        }
    }
    /**
     * @Author ZhangBo
     * @Description 更改场景的 isPublish 状态
     * @Date 15:12 2025/1/17
     * @Param [sceneId]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("更改场景发布状态")
    @PostMapping("/toggle_publish/{sceneId}")
    public R togglePublishStatus(@PathVariable Long sceneId) {
        try {
            String userId = UserContext.getUserId(); // 获取当前用户ID
            R permissions = userServiceClient.checkUserScenePermission(userId, sceneId);
            Map<String, Boolean> permissionsMap = (Map<String, Boolean>) permissions.getData();
            if (!permissionsMap.get("edit")) {
                log.error("用户没有编辑该场景的权限，userId: " + userId + ", sceneId: " + sceneId);
                return R.error("您没有编辑该场景的权限");
            }
            // 调用服务层方法更改场景发布状态
            return aiXSceneService.togglePublishStatus(sceneId);
        } catch (Exception e) {
            log.error("更改场景发布状态失败，sceneId: " + sceneId, e);
            return R.error("更改场景发布状态失败");
        }
    }

    /**
     * @Author ZhangBo
     * @Description 获取场景发布状态
     * @Date 17:21 2025/1/17
     * @Param [sceneId]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("获取场景发布状态")
    @PostMapping("/get_publish/{sceneId}")
    public R getPublishStatus(@PathVariable Long sceneId) {
        try {
            return aiXSceneService.getScenePublish(sceneId);
        } catch (Exception e) {
            log.error("更改场景发布状态失败，sceneId: " + sceneId, e);
            return R.error("更改场景发布状态失败");
        }

    }

    /**
     * @Author ZhangBo
     * @Description 开始学习和报名
     * @Date 17:24 2025/1/19
     * @Param [sceneId]
     * @return com.ilink.ilinkcommon.domain.R
     **/
    @MethodLog("开始学习和报名")
    @PostMapping("/update_start_learn_and_sign_up/{sceneId}")
    public R updateStartLearnAndSignUp(@PathVariable Long sceneId) {
        try {
            String userId = UserContext.getUserId();
            return aiXSceneService.updateStartLearnAndSignUp(sceneId, userId);
        } catch (Exception e) {
            String userId = UserContext.getUserId();
            log.error("更新开始学习和报名状态失败，sceneId: " + sceneId + ", userId: " + userId, e);
            return R.error("更新开始学习和报名状态失败");
        }
    }


    @MethodLog("根据微场景id查询所有开课记录")
    @GetMapping("/get_scene_begin_end_record")
    public R getSceneBeginEndRecords(@RequestParam Long sceneId) {
        try {
            List<AiXSceneBeginEnd> recordIds = aiXSceneService.getSceneBeginEndRecords(sceneId);
            if (recordIds.isEmpty()) {
                return R.error("开课记录查询失败");
            }
            return R.ok("获取微场景开课记录成功", recordIds);
        } catch (Exception e) {
            log.error("获取微场景开课记录失败，sceneId: " + sceneId, e);
            return R.error("获取微场景开课记录失败");
        }
    }

    @MethodLog("根据微场景ID查询微场景的agentUrl")
    @GetMapping("/get_scene_agent_url")
    public R getSceneAgentUrl(@RequestParam Long sceneId) {
        try {
            String agentUrl = aiXSceneService.getSceneAgentUrl(sceneId);
            return R.ok("获取微场景的agentUrl成功", agentUrl);
        } catch (Exception e) {
            log.error("获取微场景的agentUrl失败，sceneId: " + sceneId, e);
            return R.error("获取微场景的agentUrl失败");
        }
    }

    @MethodLog("添加微场景的agentUrl")
    @PostMapping("/add_scene_agent_url")
    public R addSceneAgentUrl(@RequestBody AiXSceneAgentUrlRequest request) {
        try {
            String result = aiXSceneService.addSceneAgentUrl(request.getSceneId(), request.getAgentUrl());
            return R.ok("添加微场景的agentUrl成功", result);
        } catch (Exception e) {
            log.error("添加微场景的agentUrl失败，sceneId: " + request.getSceneId(), e);
            return R.error("添加微场景的agentUrl失败");
        }
    }

    @MethodLog("更新微场景的agentUrl")
    @PostMapping("/update_scene_agent_url")
    public R updateSceneAgentUrl(@RequestBody AiXSceneAgentUrlRequest request) {
        try {
            String result = aiXSceneService.updateSceneAgentUrl(request.getSceneId(), request.getAgentUrl());
            return R.ok("更新微场景的agentUrl成功", result);
        } catch (Exception e) {
            log.error("更新微场景的agentUrl失败，sceneId: " + request.getSceneId(), e);
            return R.error("更新微场景的agentUrl失败");
        }
    }


}
